package com.xinruke.hostels.reservation.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Sets;
import com.xinruke.hostels.cache.extract.extractor.HotelInfoCacheExtractor;
import com.xinruke.hostels.cache.extract.extractor.ReservationCacheExtractor;
import com.xinruke.hostels.central.manage.interfaces.dto.HotelInfoDetailQueryResultDTO;
import com.xinruke.hostels.common.cache.ManageUserCache;
import com.xinruke.hostels.common.cache.ReservationUserCache;
import com.xinruke.hostels.common.constants.BusiConstant;
import com.xinruke.hostels.common.exception.ArgumentException;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.YwHuiyidanjiudianguanxi;
import com.xinruke.hostels.common.po.YwYudingHuiyiXuqiudan;
import com.xinruke.hostels.common.po.constants.HuiyidanjiudianguanxiConstants;
import com.xinruke.hostels.common.po.constants.YwYudingHuiyiDingdanConstants;
import com.xinruke.hostels.common.util.CustomSecurity;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.reservation.interfaces.dto.*;
import com.xinruke.hostels.reservation.interfaces.dto.pms.*;
import com.xinruke.hostels.reservation.mapper.YwHuiyidanjiudianguanxiMapper;
import com.xinruke.hostels.reservation.mapper.YwYudingHuiyiXuqiudanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MeetingService {

    @Resource
    private YwYudingHuiyiXuqiudanMapper ywYudingHuiyiXuqiudanMapper;

    @Resource
    private YwHuiyidanjiudianguanxiMapper huiyidanjiudianguanxiMapper;

    @Resource
    private ReservationUserCache reservationUserCache;

    @Resource
    private ReservationCacheExtractor reservationCache;
    @Resource
    private HotelInfoCacheExtractor hotelInfoCacheExtractor;

    @Autowired
    private ManageUserCache manageUserCache;


    @Transactional
    public ResultVO submit(MeetingInquerySubmitInfoDto params) {
        log.info("会议需求询价单下单接口 start---------");
        String traceId = CustomSecurity.getTraceID();
        log.info("traceId[" + traceId + "] 请求参数：reqParam=" + JSONObject.toJSONString(params));
        long startTime = System.currentTimeMillis();
        ResultVO<MeetingInquerySubmitInfoDto> resultVO = ResultVO.fail();
        List<Integer> hotelIdList = params.getHotelIdList();
        if (CollectionUtils.isEmpty(hotelIdList)) {
            resultVO.setMessage("询价单招待所信息未选择，请添加");
            return resultVO;
        }

        Set<Integer> hotelIdSet = Sets.newHashSet(hotelIdList);
        if (hotelIdSet.size() != hotelIdList.size()) {
            resultVO.setMessage("询价单招待所信息存在重复，请重新添加");
            return resultVO;
        }

        String dingdanhao = "HYDD" + String.valueOf(System.currentTimeMillis()).substring(5);

        YwYudingHuiyiXuqiudan dingdan = new YwYudingHuiyiXuqiudan();
        BeanUtils.copyProperties(params, dingdan);
        dingdan.setChuangjianshijian(new Date());
        dingdan.setTianbaoshijian(new Date());
        dingdan.setYudingriqi(new Date());
        dingdan.setGengxinshijian(new Date());
        dingdan.setDingdanhao(dingdanhao);
        dingdan.setHuiyuanId(reservationUserCache.getCurrentUserId());
        dingdan.setShanchubiaoshi(YwYudingHuiyiDingdanConstants.SHANCHUBIAOSHI_BUSHANCHU);
        dingdan.setZhuangtai(YwYudingHuiyiDingdanConstants.ZHUANGTAI_YITIJIAO);

        //校验订单类型
        byte i = 0;


       /* //是否存在客房需求
        boolean kefangxuqiu = params.getShuangrenjian() == null && params.getDanrenjian() == null && params.getTaojian() == null && params.getKefangbeizhu() == null;
        //是否存在就餐需求
        boolean jiucanxuqiu = params.getJiucanrenshu() == null && params.getJiucanbiaojia() == null;
        //是否存在车位需求 TODO 没有用到
        boolean cheweixuqiu =  params.getXiaoche() == null && params.getDache() == null;

        if (kefangxuqiu && jiucanxuqiu) {
            dingdan.setHuiyixuqiubiaoshi(YwYudingHuiyiDingdanConstants.XUQIUBIAOSHI_HUIYI);
        } else if (kefangxuqiu) {
            dingdan.setHuiyixuqiubiaoshi(YwYudingHuiyiDingdanConstants.XUQIUBIAOSHI_HUIYI_YONGCAN);
        } else if (jiucanxuqiu) {
            dingdan.setHuiyixuqiubiaoshi(YwYudingHuiyiDingdanConstants.XUQIUBIAOSHI_HUIYI_ZHUSU);
        } else {
            dingdan.setHuiyixuqiubiaoshi(YwYudingHuiyiDingdanConstants.XUQIUBIAOSHI_HUIYI_ZHUSU_YONGCAN);
        }
*/

        dingdan.setHuiyixuqiubiaoshi((params.getHuiyixuqiubiaoshi() != null && params.getHuiyixuqiubiaoshi().intValue() > 0) ? params.getHuiyixuqiubiaoshi() : BusiConstant.HUIYIXUQIUDAN_BIAOSHI_1);

        int insertCount = ywYudingHuiyiXuqiudanMapper.insertSelective(dingdan);
        if (insertCount < 1) {
            throw new ArgumentException("提交订单失败");
        }
        //加入关系表
        Integer dingdanId = dingdan.getId();
        List<YwHuiyidanjiudianguanxi> huiyidanjiudianguanxiList = params.getHotelIdList().stream().map(h -> {
            YwHuiyidanjiudianguanxi huiyidanjiudianguanxi = new YwHuiyidanjiudianguanxi();
            huiyidanjiudianguanxi.setJiudianId(h);
            huiyidanjiudianguanxi.setChuangjianshijian(new Date());
            huiyidanjiudianguanxi.setHuiyidingdanId(dingdanId);
            huiyidanjiudianguanxi.setHuiyidingdanhao(dingdanhao);
            huiyidanjiudianguanxi.setZhuangtai(HuiyidanjiudianguanxiConstants.ZHUANGTAI_DAISHENHE);
            huiyidanjiudianguanxi.setShanchubiaoshi(HuiyidanjiudianguanxiConstants.SHANCHUBIAOSHI_BUSHANCHU);
            huiyidanjiudianguanxi.setGengxinshijian(new Date());
            huiyidanjiudianguanxi.setManzuxuqiu(HuiyidanjiudianguanxiConstants.MANZHUXUQIU_WEIHUIFU);

            return huiyidanjiudianguanxi;
        }).collect(Collectors.toList());
        int insertList = huiyidanjiudianguanxiMapper.insertList(huiyidanjiudianguanxiList);
        if (insertList < 1) {
            throw new ArgumentException("提交订单失败");
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        log.info("traceId[" + traceId + "] 返回参数，takeTimes={}", DateFormatUtils.format(new Date(totalTime), "mm分ss秒SSS毫秒"));
        log.info("会议需求询价单下单接口 end---------");
        return ResultVO.success();
    }


    public ResultVO<RowsDataVO<MeetingInqueryListQueryResultDto>> list(MeetingInqueryListQueryDto params) {
        RowsDataVO<MeetingInqueryListQueryResultDto> dataVO = new RowsDataVO<>();
        ResultVO<RowsDataVO<MeetingInqueryListQueryResultDto>> resultVO = ResultVO.success();
        QueryConditions conditions = new QueryConditions();

        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, YwYudingHuiyiDingdanConstants.SHANCHUBIAOSHI_BUSHANCHU);
        conditions.addCondition("zhuangtai", EConditionOperator.EQULS, params.getZhuangtai());
        conditions.addCondition("yudingrenxingming", EConditionOperator.LIKE, params.getYudingrenxingming());
        conditions.addCondition("yudingriqi", EConditionOperator.GREATER, params.getReservationStartDate());
        conditions.addCondition("yudingriqi", EConditionOperator.LESS, params.getReservationEndDate());
        conditions.addCondition("huiyuanId", EConditionOperator.EQULS, reservationUserCache.getCurrentUserId());
        conditions.addCondition("dingdanhao", EConditionOperator.EQULS, params.getDingdanhao());

        MyExample example = new MyExample(YwYudingHuiyiXuqiudan.class, conditions, params.getOrderFields());
        Page<MeetingInqueryListQueryResultDto> page = PageHelper.startPage(params.getPageNo(), params.getPageSize());
        List<YwYudingHuiyiXuqiudan> ywYudingHuiyiDingdanList = ywYudingHuiyiXuqiudanMapper.selectByExample(example);
        List<MeetingInqueryListQueryResultDto> listQueryResultDtos = ywYudingHuiyiDingdanList.stream().map(d -> {
            MeetingInqueryListQueryResultDto resultDto = new MeetingInqueryListQueryResultDto();
            BeanUtils.copyProperties(d, resultDto);

            //得到所属关系列表
            List<YwHuiyidanjiudianguanxi> huiyidanjiudianguanxiList = huiyidanjiudianguanxiMapper.selectByExample(Example.builder(YwHuiyidanjiudianguanxi.class)
                    .where(Sqls.custom()
                            .andEqualTo("huiyidingdanId", d.getId())
                            .andEqualTo("shanchubiaoshi", HuiyidanjiudianguanxiConstants.SHANCHUBIAOSHI_BUSHANCHU)
                    ).build()
            );
            List<HotelInquiryResultDTO> hotelInquiryResultDTOList = huiyidanjiudianguanxiList.stream().map(g -> {
                HotelInquiryResultDTO hotelInquiryResultDTO = new HotelInquiryResultDTO();
                //得到酒店基本信息
                HotelInfoDetailQueryResultDTO jiudianInfoById = hotelInfoCacheExtractor.getJiudianInfoById(g.getJiudianId());
                if (jiudianInfoById != null) {
                    BeanUtils.copyProperties(jiudianInfoById, hotelInquiryResultDTO);
                    hotelInquiryResultDTO.setJiudianMingcheng(jiudianInfoById.getMingcheng());
                    hotelInquiryResultDTO.setJiudianId(g.getJiudianId());
                    hotelInquiryResultDTO.setId(g.getId());
                    hotelInquiryResultDTO.setManzuxuqiu(g.getManzuxuqiu());
                    hotelInquiryResultDTO.setCankaojia(g.getCankaojia());

                }
                //得到回应消息
                BeanUtils.copyProperties(g, hotelInquiryResultDTO);
                return hotelInquiryResultDTO;
            }).collect(Collectors.toList());
            resultDto.setHotelInquiryResultList(hotelInquiryResultDTOList);

            return resultDto;
        }).collect(Collectors.toList());


        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(listQueryResultDtos);
        resultVO.setData(dataVO);
        return resultVO;
    }


    /**
     * 根据用户酒店id和查询条件获取会议单列表
     *
     * @param params
     * @return
     */
    public ResultVO<RowsDataVO<MeetingInqueryPmsListQueryResultDto>> pmsList(MeetingInqueryPmsListQueryDto params) {
        RowsDataVO<MeetingInqueryPmsListQueryResultDto> dataVO = new RowsDataVO<>();
        ResultVO<RowsDataVO<MeetingInqueryPmsListQueryResultDto>> resultVO = ResultVO.success();
        params.setJiudianId(manageUserCache.getJiudianId());

        Page<MeetingInqueryListQueryResultDto> page = PageHelper.startPage(params.getPageNo(), params.getPageSize());
        List<MeetingInqueryPmsListQueryResultDto> ywYudingHuiyiDingdanList = huiyidanjiudianguanxiMapper.getHuiyidanjiudianguanxiList(params);
        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(ywYudingHuiyiDingdanList);
        resultVO.setData(dataVO);
        return resultVO;
    }


    public ResultVO<MeetingInqueryPmsDetailResultDto> pmsDetail(MeetingInqueryPmsDetailQueryDto params) {
        ResultVO<MeetingInqueryPmsDetailResultDto> resultVO = ResultVO.fail();
        params.setJiudianId(manageUserCache.getJiudianId());
        MeetingInqueryPmsDetailResultDto meetingInqueryPmsDetailResultDto = huiyidanjiudianguanxiMapper.getHuiyidanByParams(params);
        if (meetingInqueryPmsDetailResultDto != null) {
            resultVO = ResultVO.success();
            resultVO.setData(meetingInqueryPmsDetailResultDto);
        }
        return resultVO;
    }


    public ResultVO<MeetingInqueryDetailResultDto> detail(MeetingInqueryDetailQueryDto params) {
        ResultVO<MeetingInqueryDetailResultDto> resultVO = ResultVO.fail();
        MeetingInqueryDetailResultDto resultDto = new MeetingInqueryDetailResultDto();

        YwYudingHuiyiXuqiudan dingdan = ywYudingHuiyiXuqiudanMapper.selectByPrimaryKey(params.getId());
        BeanUtils.copyProperties(dingdan, resultDto);
        List<YwHuiyidanjiudianguanxi> huiyidanjiudianguanxiList = huiyidanjiudianguanxiMapper.selectByExample(Example.builder(YwHuiyidanjiudianguanxi.class)
                .where(Sqls.custom()
                        .andEqualTo("huiyidingdanId", dingdan.getId())
                        .andEqualTo("shanchubiaoshi", HuiyidanjiudianguanxiConstants.SHANCHUBIAOSHI_BUSHANCHU)
                ).build()
        );
        List<MeetingInquiryHotelResultDTO> meetingInquiryHotelResultDTOList = huiyidanjiudianguanxiList.stream().map(h -> {
            MeetingInquiryHotelResultDTO resultDTO = new MeetingInquiryHotelResultDTO();

            HotelInfoDetailQueryResultDTO jiudianInfoQueryDTO = hotelInfoCacheExtractor.getJiudianInfoById(h.getJiudianId());
            if (jiudianInfoQueryDTO != null) {
                BeanUtils.copyProperties(jiudianInfoQueryDTO, resultDTO);
                resultDTO.setJiudianId(jiudianInfoQueryDTO.getId());
                resultDTO.setJiudianMingcheng(jiudianInfoQueryDTO.getMingcheng());
            }
            return resultDTO;
        }).collect(Collectors.toList());
        resultDto.setHotelIdList(meetingInquiryHotelResultDTOList);
        resultVO = ResultVO.success();
        resultVO.setData(resultDto);

        return resultVO;
    }


    @Transactional
    public ResultVO verify(MeetingVerifyQueryDTO params) {
        huiyidanjiudianguanxiMapper.rejectHotelInfo(params.getOrderId());
        huiyidanjiudianguanxiMapper.verifyHotelInfo(params.getInfoId());
        YwYudingHuiyiXuqiudan ywYudingHuiyiDingdan = new YwYudingHuiyiXuqiudan();
        ywYudingHuiyiDingdan.setId(params.getOrderId());
        ywYudingHuiyiDingdan.setZhuangtai(YwYudingHuiyiDingdanConstants.ZHUANGTAI_YIHUIFU);
        int i = ywYudingHuiyiXuqiudanMapper.updateByPrimaryKeySelective(ywYudingHuiyiDingdan);
        if (i == 0) {
            throw new ArgumentException("修改订单状态失败");
        }
        return ResultVO.success();
    }


    @Transactional
    public ResultVO audit(MeetingInqueryAuditQueryDTO params) {
        ResultVO<PersonalBookingResultDTO> resultVO = ResultVO.fail();
        YwHuiyidanjiudianguanxi ywHuiyidanjiudianguanxiQueryVo = huiyidanjiudianguanxiMapper.selectByPrimaryKey(params.getInfoId());
        if (ywHuiyidanjiudianguanxiQueryVo != null) {
            if (ywHuiyidanjiudianguanxiQueryVo.getZhuangtai().intValue() > 1) {
                resultVO.setMessage("该订单已进行审核处理");
                return resultVO;
            }
            //1.更新需求关系单状态
            YwHuiyidanjiudianguanxi huiyidanjiudianguanxi = new YwHuiyidanjiudianguanxi();
            huiyidanjiudianguanxi.setId(params.getInfoId());
            huiyidanjiudianguanxi.setZhuangtai(params.getShenhezhuangtai());
            //huiyidanjiudianguanxi.setManzuxuqiu((byte) (params.getShenhezhuangtai() == 2 ? 1 : 0));
            huiyidanjiudianguanxiMapper.updateByPrimaryKeySelective(huiyidanjiudianguanxi);

            //2.更新需求单状态，由已提交1改为已回复2,如果查询不到不进行更新操作
            /*YwYudingHuiyiXuqiudan ywYudingHuiyiDingdan = new YwYudingHuiyiXuqiudan();
            ywYudingHuiyiDingdan.setId(ywHuiyidanjiudianguanxiQueryVo.getHuiyidingdanId());
            ywYudingHuiyiDingdan.setZhuangtai(YwYudingHuiyiDingdanConstants.ZHUANGTAI_YITIJIAO);
            YwYudingHuiyiXuqiudan ywYudingHuiyiDingdanQueryVo = ywYudingHuiyiXuqiudanMapper.selectOne(ywYudingHuiyiDingdan);
            if (ywYudingHuiyiDingdanQueryVo != null) {
                YwYudingHuiyiXuqiudan ywYudingHuiyiDingdanUpVo = new YwYudingHuiyiXuqiudan();
                ywYudingHuiyiDingdanUpVo.setId(ywYudingHuiyiDingdanQueryVo.getId());
                ywYudingHuiyiDingdanUpVo.setZhuangtai(YwYudingHuiyiDingdanConstants.ZHUANGTAI_YIHUIFU);
                ywYudingHuiyiXuqiudanMapper.updateByPrimaryKeySelective(ywYudingHuiyiDingdanUpVo);
            }*/
            return ResultVO.success();
        }
        return resultVO;
    }
}
